﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Net;

using System.Windows.Forms;
namespace WP7TransferDataTool
{
    public class ServiceHostCtrl 
    {
        private static ServiceHost serviceHost;
        public static void StartService(string hostName)
        {
            Uri baseAddress = new Uri(string.Format("http://{0}:18000/TransferDataService/", hostName));
            serviceHost = new ServiceHost(typeof(TransferDataService), baseAddress);
            try
            {
                serviceHost.Open();
            }
            catch (AddressAccessDeniedException ex)
            {
                serviceHost.Abort();
                MessageBox.Show("Run the application as administrator", "Access is denied", MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            catch
            {
                serviceHost.Abort();
                throw;
            }
        }

        public static CommunicationState ServiceState
        {
            get 
            {
                if (serviceHost == null)
                {
                    return CommunicationState.Closed;
                }
                else
                {
                    return serviceHost.State;
                }
            }
        }

        public static void StopService()
        {
            if (serviceHost != null)
            {
                if (serviceHost.State == CommunicationState.Opened)
                {
                    serviceHost.Close();
                }
            }
        }
    }
}
